//
//  WBMainViewController.swift
//  仿新浪微博
//
//  Created by 罗超 on 2017/5/3.
//  Copyright © 2017年 LuoChao. All rights reserved.
//

import UIKit

class WBMainViewController: UITabBarController {
    
    // 定时器
    fileprivate var timer: Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupChildControllers()
        setupComposeButton()
        setupTimer()
        
        // 设置代理
        delegate = self
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        // 销毁定时器
        timer?.invalidate()
        // 注销通知
        NotificationCenter.default.removeObserver(self)
    }

    // MARK: 设置屏幕方向
    /**
        - 3.1 设置屏幕方向由 函数 变为 getter
        - 使用代码设置后,当前的控制器及自控制器都会遵守这个方向!
        - 如果是播放视屏,通常是通过 modal 展现的!
    */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    // 通知监听方法
    @objc fileprivate func userLogin(n: Notification) {
        print("用户登录通知 \(n)")
        
        // 展现登录控制器
        let nav = UINavigationController(rootViewController: WBOAuthViewController())
        
        present(nav, animated: true, completion: nil)
    }
    
    //MARK: 监听撰写按钮
    /**
        - swift 3 fileprivate 修饰仅在当前对象被访问
        - @objc 允许这个函数在"运行时"通过 OC 的消息机制被调用!
    */
    @objc fileprivate func composeStatus() {
        print("撰写微博")
        
        //测试屏幕方向旋转
        let vc = UIViewController()
        
        vc.view.backgroundColor = UIColor.cz_random()
        
        let navi = UINavigationController(rootViewController: vc)
        
        present(navi, animated: true, completion: nil)
        
    }
    
    // MARK: 私有控件
    fileprivate lazy var composeButton: UIButton = UIButton.cz_imageButton(
        "tabbar_compose_icon_add",
        backgroundImageName: "tabbar_compose_button")
    
}

// MARK: UITabBarControllerDelegate
extension WBMainViewController:UITabBarControllerDelegate {
    
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        // 获取控制器索引
        let index = viewControllers?.index(of: viewController)
        
        if selectedIndex == index && index == 0 {
            let nav = viewController as! UINavigationController
            let vc = nav.childViewControllers.first as! WBHomeViewController
            // 滚动到顶部
            vc.tableView?.scrollToRow(at: IndexPath(row: 0, section: 0), at: UITableViewScrollPosition(rawValue: 0)!, animated: true)
            // 刷新数据,延迟解决跳转不正确问题，保证表格先滚动到顶部再刷新数据
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: { 
                vc.loadData()
            })
        }
        
        // 判断目标控制器是否是 UIViewController
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK: 定时器相关方法
extension WBMainViewController {
    
    /// 定义时钟
    func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 15.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    /// 时钟触发方法
    @objc fileprivate func updateTimer() {
        
        if !WBNetworkManager.shared.userLogon {
            return
        }
        
        WBNetworkManager.shared.unreadCount { (count) in
            // 设置 tabBarItem 的 badgeNumber
            self.tabBar.items?.first?.badgeValue = count>0 ? "\(count)" : nil
            
            // 设置 App 的 badgeNumber，从 iOS 8.0 以后需要用户授权之后才能显示
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

/**
    - extension 类似于 OC 中的 分类,在Swift中还可以用来切分代码块
    - 可以把相近功能的函数,放在一个 extension 中,便于代码维护
    - 注意:和 OC 的分类一样, extension 中不能定义属性
*/
extension WBMainViewController {
    
    //MARK: 设置撰写按钮
    fileprivate func setupComposeButton(){
        tabBar.addSubview(composeButton)
        
        //设置按钮位置
        let count = childViewControllers.count
        //将缩进宽度减少,放大按钮宽度,盖住容错点,防止穿帮
        //let w = tabBar.bounds.width / CGFloat(count) - 1
        // 用 UITabBarControllerDelegate 判断，解决
        let w = tabBar.bounds.width / CGFloat(count)
        
        //CGRectInset 正数向内缩进,负数向外扩展
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        //按钮监听
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
    }
    
    //MARK: 设置所有子控制器
    fileprivate func setupChildControllers() {
        
        // 获取沙盒文件
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        var data = NSData(contentsOfFile: jsonPath)
        if data == nil {
            // 如果沙盒没有, 从 bundle 加载
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        
        // 从 bundle 加载配置的 json
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String: AnyObject]]
            else {
                return
        }
        
        /*
        let array = [
            ["clsName" : "WBHomeViewController", "title" : "首页", "imageName" : "home",
             "visitorInfo" : ["imageName" : "", "message" : "关注一些人，回这里看看有什么惊喜"]
            ],
            ["clsName" : "WBMessageViewController", "title" : "消息", "imageName" : "message_center",
             "visitorInfo" : ["imageName" : "visitordiscover_image_message", "message" : "登录后，别人评论你的微博，发给你的消息，都会在这里收到通知"]
            ],
            ["clsName" : "UIViewController"],
            ["clsName" : "WBDiscoverViewController", "title" : "发现", "imageName" : "discover",
             "visitorInfo" : ["imageName" : "visitordiscover_image_message", "message" : "登录后，最新、最热微博尽在掌握，不再会与实事潮流擦肩而过"]
            ],
            ["clsName" : "WBProfileViewController", "title" : "我", "imageName" : "profile",
             "visitorInfo" : ["imageName" : "visitordiscover_image_profile", "message" : "登录后，你的微博、相册、个人资料会显示在这里，展示给别人"]
            ]
        ]
         
         // 可以储存到沙盒,检测数据格式是否正确
         //(array as NSArray).write(toFile: "/Users/luochao/Desktop/demo.plist", atomically: true)
         
        */
        
        /* 
         //数组 -> json 序列化
         //OC方式代码
        let data = try! JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
        (data as NSData).write(toFile: "/Users/luochao/Desktop/config.json", atomically: true)
 
         // swift 代码
        do {
            let data = try JSONSerialization.data(withJSONObject: array, options: [.prettyPrinted])
            let filePath = URL(fileURLWithPath: "/Users/luochao/Desktop/config.json")
            try data.write(to: filePath, options: [])
        } catch  {
            print(error)
        }
        */
        
        // 遍历数组,循环创建子控制器
        var arrayM = [UIViewController]()
        for dict in array! {
            
            arrayM.append(controller(dict: dict))
            
        }
        
        // 设置 tabBar 子控制器
        viewControllers = arrayM
        
    }
    
    //MARK: 使用字典创建一个自控制器
    /// - Parameter dict: 信息字典
    /// - Returns: 子控制器
    fileprivate func controller(dict: [String: AnyObject]) -> UIViewController {
        
        guard let clsName = dict["clsName"] as? String,
        let title = dict["title"] as? String,
        let imageName = dict["imageName"] as? String,
        let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseViewController.Type,
        let visitorDict = dict["visitorInfo"] as? [String: String]
            
            else {
            
            return UIViewController()
        }
        
        //创建视图控制器
        let vc = cls.init()
        
        vc.title = title
        
        //设置访客信息字典
        vc.visitorInfoDictionary = visitorDict
        
        //设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        //设置 tabbar 的标题字体,字体大小要设置normal状态
        vc.tabBarItem.setTitleTextAttributes(
            [NSAttributedStringKey.foregroundColor : UIColor.orange],
            for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes(
            [NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12)],
            for: .normal)
        
        /* 经测试 10 的设置字体跟颜色没有变化 Swift3.1
        if #available(iOS 10, *) {
            vc.tabBarItem.setBadgeTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .highlighted)
            vc.tabBarItem.setBadgeTextAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 24)], for: .normal)
        } else {
            vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName : UIColor.orange], for: .highlighted)
            vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName : UIFont.systemFont(ofSize: 12)], for: .normal)
        }
        */
        
        //实例化导航控制器的时候,会调用 push 方法将 rootVc 压栈
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
    }
    
}

